import aiohttp
import asyncio
import json
import datetime
from app import logger
from libs.zhuque_listBetgame import getgamelist
from config import ZHUQUE_COOKIE, ZHUQUE_CSRF

# 配置区，运行前填好配置
cookie_headers = {"Cookie": ZHUQUE_COOKIE, "X-Csrf-Token": ZHUQUE_CSRF}
url = "https://zhuque.in/api/gaming/placeABet2"
setgame_id = 0
setgame_amount = 0
setteam_id = 0


async def placeABet2(game_id, game_amount, team_id):
    try:
        async with aiohttp.ClientSession() as session:
            code_commade = ""
            async with session.post(
                url,
                headers=cookie_headers,
                json={"id": game_id, "bonus": game_amount, "option": team_id},
            ) as response:
                json_response = await response.json()

                if response.status == 200:
                    code_commade = json_response.get("code")
                    logger.info(f"Request successful: {json_response}")
                else:
                    code_commade = json_response
                    logger.error(f"Request failed with status {json_response}")

                return code_commade
    except aiohttp.ClientError as e:
        logger.error(f"Client error occurred: {e}")
        return f"Client error: {str(e)}"
    except Exception as e:
        logger.error(f"An unexpected error occurred: {e}")
        return f"Unexpected error: {str(e)}"


async def main(game_id, game_amount, team_id):

    recode_commade = await placeABet2(game_id, game_amount, team_id)
    teame = await getgamelist(game_id)
    if "SUCCESS" in recode_commade:
        result_code = 1
        result_mess = f"朱雀菠菜 {teame[0]} vs {teame[1]} 的比赛,下注 {teame[team_id]} 队伍 {game_amount} 灵石成功"
        logger.info(
            f"朱雀菠菜 {teame[0]} vs {teame[1]} 的比赛,下注 {teame[team_id]} 队伍 {game_amount} 灵石成功"
        )
    else:
        result_code = 0
        if teame:
            result_mess = f"朱雀菠菜 {teame[0]} vs {teame[1]} 的比赛,下注 {teame[team_id]} 队伍 {game_amount} 灵石失败"
            logger.info(
                f"朱雀菠菜 {teame[0]} vs {teame[1]} 的比赛,下注 {teame[team_id]} 队伍 {game_amount} 灵石失败"
            )

        else:
            result_code = 0
            result_mess = f"朱雀菠菜 ID:{game_id} 的比赛 ,下注 {team_id} 队伍 {game_amount} 灵石失败"
            logger.info(
                f"朱雀菠菜 ID:{game_id} 的比赛 ,下注 {team_id} 队伍 {game_amount} 灵石失败"
            )

    return result_code, result_mess


# 运行主函数
if __name__ == "__main__":
    asyncio.run(main(setgame_id, setgame_amount, setteam_id))
